package com.lijian.search.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lijian.search.dao.SearchDao;
import com.lijian.search.pojo.SearchItem;
import com.lijian.search.pojo.SearchResult;

/**
 * <p>Title: SearchDaoImpl.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * @author lijian
 * @date 2017年4月16日下午9:37:49
 * @version 1.0
 */
@Repository
public class SearchDaoImpl implements SearchDao {

	@Autowired
	private SolrServer solrServer;
	@Override
	public SearchResult search(SolrQuery query) throws SolrServerException {
		QueryResponse response = solrServer.query(query);
		SolrDocumentList results = response.getResults();
		List<SearchItem> itemList=new ArrayList<>();
		for(SolrDocument doc:results){
			SearchItem item=new SearchItem();
			item.setId((String) doc.get("id"));
			item.setCategory_name((String) doc.get("item_category_name"));
			item.setImage((String) doc.get("item_image"));
			item.setItem_desc((String) doc.get("item_desc"));
			item.setPrice((Long) doc.get("item_price"));
			item.setSell_point((String) doc.get("item_sell_point"));
			//取高亮
			Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
			List<String> list = highlighting.get(doc.get("id")).get("item_title");
			String itemTitle="";
			if(list!=null && list.size()>0){
				 itemTitle = list.get(0);
			}else{
				itemTitle = (String) doc.get("item_title");
			}
			item.setTitle(itemTitle);
			itemList.add(item);
		} 
		SearchResult result=new SearchResult();
		result.setItemList(itemList);
		result.setRecordCount(results.getNumFound());
		return result;
	}

}
